package com.platform.modules.cpt.controller;

import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.platform.common.page.PageUtil;
import com.platform.common.utils.RestResponse;
import com.platform.modules.cpt.dto.ListByAppByAppDto;
import com.platform.modules.cpt.entity.CptAcceptanceEntity;
import com.platform.modules.cpt.entity.CptAcceptanceSuperviseEntity;
import com.platform.modules.cpt.service.CptAcceptanceService;
import com.platform.modules.cpt.service.CptAcceptanceSuperviseService;
import com.platform.modules.quality.entity.QlyAcceptanceEntity;
import com.platform.modules.quality.vo.CommonResult;
import com.platform.modules.sys.controller.AbstractController;
import com.platform.modules.sys.entity.SysUserEntity;
import com.platform.util.DocUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * Controller
 *
 * @author biaohuaming
 * @date 2020-02-24 15:28:20
 */
@Api(tags = "竣工验收监督记录")
@RestController
@RequestMapping("cpt/acceptance/supervise")
public class CptAcceptanceSuperviseController extends AbstractController {


    @Autowired
    private CptAcceptanceSuperviseService cptAcceptanceSuperviseService;

    @Autowired
    private CptAcceptanceService cptAcceptanceService;
    
    @Autowired
    private DocUtil docUtil;



    /**
     * @descr 查询详情<br> 暂不使用
     * @param cptAcceptanceId 竣工验收监督申请记录ID
     * @return
     */
    @ApiOperation(value = "查询详情")
    @GetMapping("/view")
    public RestResponse view(@RequestParam String cptAcceptanceId) {
    	Map<String, Object> params = getParams();
    	params.put("cptId", cptAcceptanceId);
    	CptAcceptanceSuperviseEntity entity = cptAcceptanceSuperviseService.queryOne(params);
        return RestResponse.success().put("data", entity);
    } 

    /**
     * @descr 查询详情app<br>
     * @param prjId 项目ID
     * @param businessId 竣工验收申请ID
     * @return
     */
    @ApiOperation(value = "查询详情app")
    @GetMapping("/app/view")
    public CommonResult appView(@RequestParam(required=false) String prjId, @RequestParam(required=false) String businessId) {
    	CptAcceptanceSuperviseEntity entity = null;
    	//待办项进入
    	if(StringUtils.isNotEmpty(businessId)) {
	    	Map<String, Object> params2 = new HashMap<String, Object>();
	    	params2.put("cptId", businessId);
	    	entity = cptAcceptanceSuperviseService.queryOne(params2);
    	}else {
    		//TODO 这里还没有加入权限校验
	    	Map<String, Object> params = new HashMap<String, Object>();
	    	params.put("prjId", prjId);
	    	params.put("status", new String[] {"2"});
	    	CptAcceptanceEntity cptAcceptanceEntity = cptAcceptanceService.queryOne(params);
	    	if(null==cptAcceptanceEntity) {
	    		return CommonResult.error("未找到竣工验收申请记录");
	    	}
	    	Map<String, Object> params2 = new HashMap<String, Object>();
	    	params2.put("cptId", cptAcceptanceEntity.getId());
	    	entity = cptAcceptanceSuperviseService.queryOne(params2);
    	}
        return CommonResult.success(entity);
    } 
    
    /**
     * @param cptAcceptanceTeamEntity
     * @return
     */
    @ApiOperation(value = "保存")
    @PostMapping("save")
    public CommonResult<CptAcceptanceSuperviseEntity> save(@RequestBody CptAcceptanceSuperviseEntity cptAcceptanceSuperviseEntity) {
    	SysUserEntity sysUserEntity = this.getUser();
    	
    	//APP第一次录入
    	if(null==cptAcceptanceSuperviseEntity.getId()) {
    		String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    		cptAcceptanceSuperviseEntity.setId(uuid);
    		cptAcceptanceSuperviseEntity.setCreateTime(new Date());
    		cptAcceptanceSuperviseEntity.setCreateUser(sysUserEntity.getUserId());
    	//PC端保存	
    	}else if(null==cptAcceptanceSuperviseEntity.getCreateTime()) {
    		cptAcceptanceSuperviseEntity.setCreateTime(new Date());
    		cptAcceptanceSuperviseEntity.setCreateUser(sysUserEntity.getUserId());
    	}else {
    	//pc&app保存	
    		cptAcceptanceSuperviseEntity.setUpdateTime(new Date());
    		cptAcceptanceSuperviseEntity.setUpdateUser(sysUserEntity.getUserId());
    	}
    	cptAcceptanceSuperviseService.saveOrUpdate(cptAcceptanceSuperviseEntity);
        return CommonResult.success(cptAcceptanceSuperviseEntity);
    }
    
    /**
     * APP查询 竣工验收监督记录
     * @param queryDto
     * @return
     */
    @ApiOperation(value = "APP查询 竣工验收监督记录")
    @PostMapping("/app/list")
    public CommonResult<Page<CptAcceptanceSuperviseEntity>> listByApp(@RequestBody ListByAppByAppDto queryDto) {
    	Map<String, Object> params = new HashMap<>();
        params.put("page", PageUtil.getCurrPage(queryDto.getPage()));
        params.put("limit", PageUtil.getLimit(queryDto.getLimit()));
        params.put("prjId", queryDto.getPrjId());
    	Page<CptAcceptanceSuperviseEntity> page = cptAcceptanceSuperviseService.queryPageByApp(params);
    	return CommonResult.success(page);
    }

    
    @ApiOperation(value = "上传 - 质量验收图片")
    @PostMapping("/app/pic")
    public RestResponse saveAcceptancePic(MultipartFile file, String accId) {
    	docUtil.createAtt(file, "", accId);
        return RestResponse.success();
    }
    
    
    @ApiOperation(value = "查询 - 质量验收图片列表")
    @GetMapping("/app/pic")
    public RestResponse getAcceptancePic(String accId) {
        return RestResponse.success().put("list", docUtil.getAttListByAttBusinessId(accId));
    }
    
    
    @ApiOperation(value = "删除 - 质量验收图片")
    @DeleteMapping("/app/pic")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "delete", name = "attIds", value = "文件id(支持多个,逗号分割)", dataType = "String")
    })
    public RestResponse deleteAcceptancePic(String attIds) {
    	if(StringUtils.isNotBlank(attIds)) {
    		docUtil.deleteAtts(Arrays.asList(attIds.split(",")));
    	}
        return RestResponse.success();
    }
    
       

    /**
     * 生成 工程竣工验收监督记录一(后续盖章)
     * @param cptAcceptanceEntity
     * @return
     */
    @ApiOperation(value = "生成-工程竣工验收监督记录一(后续盖章)")
    @PostMapping("/gcjgysjdjl1File/create")
    public CommonResult createGcjgysjdjl1File(@RequestBody CptAcceptanceEntity cptAcceptanceEntity) {
    	Map<String, Object> result = cptAcceptanceSuperviseService.createGcjgysjdjl1File(cptAcceptanceEntity, "工程竣工验收监督记录（一）.pdf");
        return CommonResult.success(result);
    }
    
    @ApiOperation(value = "下载-工程竣工验收监督记录一 文件流")
    @GetMapping("/gcjgysjdjl1File/download")
    public void downloadGcjgysjdjl1File(@RequestParam String cptId, HttpServletRequest request, HttpServletResponse response) {
    	cptAcceptanceSuperviseService.downloadGcjgysjdjlFile(cptId, request, response, "CPT_ACCPTANCE_FILES_GCJGYSJDJL1");
    }
    
    @ApiOperation(value = "下载-工程竣工验收监督记录一 文件")
    @GetMapping("/gcjgysjdjl1File/sign/download")
    public void downloadSignGcjgysjdjl1File(@RequestParam String cptId, HttpServletRequest request, HttpServletResponse response) {
    	cptAcceptanceSuperviseService.downloadSignGcjgysjdjlFile(cptId, request, response, "CPT_ACCPTANCE_FILES_GCJGYSJDJL1");
    }
    

    @ApiOperation(value = "盖章-工程竣工验收监督记录一 文件")
    @PostMapping("/gcjgysjdjl1File/sign")
    public RestResponse signGcjgysjdjl1File(HttpServletRequest request,MultipartFile file, 
    		@RequestParam String cptId, 
    		@RequestParam String attId,
    		@RequestParam(required=false) String fileName) {
    	
    	//获取已签章的合同
        String contentType = request.getContentType();
        
        if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) {
        	cptAcceptanceSuperviseService.signGcjgysjdjlFile(request, cptId, "CPT_ACCPTANCE_FILES_GCJGYSJDJL1", "工程竣工验收监督记录（一）.pdf");
        }else {
        	RestResponse.error();
        }
        return RestResponse.success();
    }
    

    /**
     * 生成工程竣工验收监督记录二(后续盖章)
     * @param cptAcceptanceEntity
     * @return
     */
    @ApiOperation(value = "生成-工程竣工验收监督记录二(后续盖章)")
    @PostMapping("/gcjgysjdjl2File/create")
    public CommonResult createGcjgysjdjl2File(@RequestBody CptAcceptanceEntity cptAcceptanceEntity) {
    	Map<String, Object> result = cptAcceptanceSuperviseService.createGcjgysjdjl2File(cptAcceptanceEntity, "工程竣工验收监督记录（二）.pdf");
        return CommonResult.success(result);
    }
    
    @ApiOperation(value = "下载-工程竣工验收监督记录二 文件流")
    @GetMapping("/gcjgysjdjl2File/download")
    public void downloadGcjgysjdjl2File(@RequestParam String cptId, HttpServletRequest request, HttpServletResponse response) {
    	cptAcceptanceSuperviseService.downloadGcjgysjdjlFile(cptId, request, response, "CPT_ACCPTANCE_FILES_GCJGYSJDJL2");
    }
    
    @ApiOperation(value = "下载-工程竣工验收监督记录二文件")
    @GetMapping("/gcjgysjdjl2File/sign/download")
    public void downloadSignGcjgysjdjl2File(@RequestParam String cptId, HttpServletRequest request, HttpServletResponse response) {
    	cptAcceptanceSuperviseService.downloadSignGcjgysjdjlFile(cptId, request, response, "CPT_ACCPTANCE_FILES_GCJGYSJDJL2");
    }
    

    @ApiOperation(value = "盖章-工程竣工验收监督记录二 文件")
    @PostMapping("/gcjgysjdjl2File/sign")
    public RestResponse signGcjgysjdjl2File(HttpServletRequest request,MultipartFile file, 
    		@RequestParam String cptId, 
    		@RequestParam String attId,
    		@RequestParam(required=false) String fileName) {
    	
    	//获取已签章的合同
        String contentType = request.getContentType();
        
        if (contentType != null && contentType.toLowerCase().startsWith("multipart/")) {
        	cptAcceptanceSuperviseService.signGcjgysjdjlFile(request, cptId, "CPT_ACCPTANCE_FILES_GCJGYSJDJL2", "工程竣工验收监督记录（二）.pdf");
        }else {
        	RestResponse.error();
        }
        return RestResponse.success();
    }
}
